﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Yuebon.Car.Application;
using Yuebon.Car.Dtos;
using Yuebon.Car.IServices;
using Yuebon.Car.Models;
using Yuebon.CMS.IServices;
using Yuebon.CMS.Models;
using Yuebon.Commons.Helpers;
using Yuebon.Commons.Log;
using Yuebon.Commons.Models;
using Yuebon.WebApp.Controllers;
using Yuebon.WebApp.Models;

namespace Yuebon.WebApp.Areas.Car.Controllers
{
    [Area("Car")]
    [Route("Car/[controller]/[action]")]
    public class AutoDetailsController : BusinessController<AutoDetails, IAutoDetailsService>
    {

        private IAlbumsService albumsService;
        public AutoDetailsController(IAutoDetailsService _iService, IAlbumsService _albumsService) : base(_iService)
        {
            iService = _iService;
            albumsService = _albumsService;
            AuthorizeKey.InsertKey = "AutoDetails/Add";
            AuthorizeKey.UpdateKey = "AutoDetails/Edit";
            AuthorizeKey.DeleteKey = "AutoDetails/Delete";
            AuthorizeKey.UpdateEnableKey = "AutoDetails/Enable";
            AuthorizeKey.ListKey = "AutoDetails/List";
            AuthorizeKey.ViewKey = "AutoDetails/View";
        }

        protected override void OnBeforeInsert(AutoDetails info)
        {

            //留给子类对参数对象进行修改
            info.Id = GuidUtils.CreateNo();
            info.CreatorTime = DateTime.Now;
            info.CreatorUserId = CurrentUser.Id;
            info.DeleteMark = false;
            if (info.SortCode == null)
            {
                info.SortCode = 99;
            }
        }

        /// <summary>
        /// 在更新数据前对数据的修改操作
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        protected override void OnBeforeUpdate(AutoDetails info)
        {
            //留给子类对参数对象进行修改 
            info.LastModifyTime = DateTime.Now;
            info.LastModifyUserId = CurrentUser.Id;
            if (info.SortCode == null)
            {
                info.SortCode = 99;
            }
        }

        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public  IActionResult InsertNew(AutoDetailsDto info)
        {
            //检查用户是否有权限，否则抛出MyDenyAccessException异常
            CheckAuthorized(AuthorizeKey.InsertKey);
            AutoDetails autoDetailsInfo = new AutoDetails();
            CommonResult result = new CommonResult();
            AutoDetails autoDetails = iService.GetWhere(string.Format("GoodsCode='{0}'", info.GoodsCode));
            if (autoDetails != null)
            {
                result.ErrMsg = "货号重复，请修改";
                result.ErrCode = "43001";
            }
            else
            {
                autoDetailsInfo.BrandId = info.BrandId;
                OnBeforeInsert(autoDetailsInfo);
                autoDetailsInfo.MemberId = info.MemberId;
                autoDetailsInfo.GoodsCode = info.GoodsCode;
                autoDetailsInfo.Title = info.Title;
                autoDetailsInfo.SubTitle = info.SubTitle;
                autoDetailsInfo.MSRP = info.MSRP;
                autoDetailsInfo.DownPayment = info.DownPayment;
                autoDetailsInfo.MonthInstallment = info.MonthInstallment;
                autoDetailsInfo.NumberOfPeriods = info.NumberOfPeriods;
                autoDetailsInfo.DownPaymentone = info.DownPaymentone;
                autoDetailsInfo.MonthInstallmentone = info.MonthInstallmentone;
                autoDetailsInfo.NumberOfPeriods1 = info.NumberOfPeriods1;
                autoDetailsInfo.DownPaymenttwo = info.DownPaymenttwo;
                autoDetailsInfo.MonthInstallmenttwo = info.MonthInstallmenttwo;
                autoDetailsInfo.NumberOfPeriods2 = info.NumberOfPeriods2;
                autoDetailsInfo.SalesPrice = info.SalesPrice;
                autoDetailsInfo.Preferential = info.Preferential;
                autoDetailsInfo.Tags = info.Tags;
                autoDetailsInfo.ImgUrl = info.ImgUrl;
                autoDetailsInfo.LinkUrl = info.LinkUrl;
                autoDetailsInfo.SeoTitle = info.SeoTitle;
                autoDetailsInfo.SeoKeywords = info.SeoKeywords;
                autoDetailsInfo.SeoDescription = info.SeoDescription;
                autoDetailsInfo.EnabledMark = info.EnabledMark;
                autoDetailsInfo.IsMsg = info.IsMsg;
                autoDetailsInfo.IsOpen = info.IsOpen;
                autoDetailsInfo.IsTop = info.IsTop;
                autoDetailsInfo.IsRed = info.IsRed;
                autoDetailsInfo.IsHot = info.IsHot;
                autoDetailsInfo.IsSlide = info.IsSlide;
                autoDetailsInfo.Click = info.Click;
                autoDetailsInfo.LikeCount = info.LikeCount;
                autoDetailsInfo.Source = info.Source;
                autoDetailsInfo.Author = info.Author;
                autoDetailsInfo.Zhaiyao = info.Zhaiyao;
                autoDetailsInfo.Description = info.Description;

                long ln = iService.Insert(autoDetailsInfo);

                string[] albumsStr=info.AlbumsPaths.Split(",");
                for(int i = 0; i <= albumsStr.Count()-1; i++)
                {
                    if (albumsStr[i] != "")
                    {
                        Albums albums = new Albums();
                        albums.Id = GuidUtils.CreateNo();
                        albums.Channel = "Car";
                        albums.ThumbPath = albumsStr[i];
                        albums.OriginalPath = albumsStr[i];
                        albums.ContentId = autoDetailsInfo.Id;
                        albums.Remark = "";
                        albums.AddTime = DateTime.Now;
                        albumsService.Insert(albums);
                    }
                }
                if (ln >= 0)
                {
                    result.ErrCode = ErrCode.successCode;
                    result.ErrMsg = ErrCode.err0;
                    result.Success = true;
                }
                else
                {
                    result.ErrMsg = ErrCode.err43001;
                    result.ErrCode = "43001";
                }
            }
            return ToJsonContent(result);
        }

        public  IActionResult Update(AutoDetailsDto info, string id)
        {
            //检查用户是否有权限，否则抛出MyDenyAccessException异常
            CheckAuthorized(AuthorizeKey.UpdateKey);
            AutoDetails autoDetailsInfo = iService.Get(id);
            CommonResult result = new CommonResult();
            AutoDetails autoDetails = iService.GetWhere(string.Format("GoodsCode='{0}' and  Id<> '{1}'", autoDetailsInfo.GoodsCode, autoDetailsInfo.Id));
            if (autoDetails != null)
            {
                result.ErrMsg = "货号已有车型，请重新输入货号";
                result.ErrCode = "43001";
            }
            else
            {
                autoDetailsInfo.BrandId = info.BrandId;
                autoDetailsInfo.MemberId = info.MemberId;
                autoDetailsInfo.GoodsCode = info.GoodsCode;
                autoDetailsInfo.Title = info.Title;
                autoDetailsInfo.SubTitle = info.SubTitle;
                autoDetailsInfo.MSRP = info.MSRP;
                autoDetailsInfo.DownPayment = info.DownPayment;
                autoDetailsInfo.MonthInstallment = info.MonthInstallment;
                autoDetailsInfo.NumberOfPeriods = info.NumberOfPeriods;
                autoDetailsInfo.DownPaymentone = info.DownPaymentone;
                autoDetailsInfo.MonthInstallmentone = info.MonthInstallmentone;
                autoDetailsInfo.NumberOfPeriods1 = info.NumberOfPeriods1;
                autoDetailsInfo.DownPaymenttwo = info.DownPaymenttwo;
                autoDetailsInfo.MonthInstallmenttwo = info.MonthInstallmenttwo;
                autoDetailsInfo.NumberOfPeriods2 = info.NumberOfPeriods2;
                autoDetailsInfo.SalesPrice = info.SalesPrice;
                autoDetailsInfo.Preferential = info.Preferential;
                autoDetailsInfo.Tags = info.Tags;
                autoDetailsInfo.ImgUrl = info.ImgUrl;
                autoDetailsInfo.LinkUrl = info.LinkUrl;
                autoDetailsInfo.SeoTitle = info.SeoTitle;
                autoDetailsInfo.SeoKeywords = info.SeoKeywords;
                autoDetailsInfo.SeoDescription = info.SeoDescription;
                autoDetailsInfo.EnabledMark = info.EnabledMark;
                autoDetailsInfo.IsMsg = info.IsMsg;
                autoDetailsInfo.IsOpen = info.IsOpen;
                autoDetailsInfo.IsTop = info.IsTop;
                autoDetailsInfo.IsRed = info.IsRed;
                autoDetailsInfo.IsHot = info.IsHot;
                autoDetailsInfo.IsSlide = info.IsSlide;
                autoDetailsInfo.Click = info.Click;
                autoDetailsInfo.LikeCount = info.LikeCount;
                autoDetailsInfo.Source = info.Source;
                autoDetailsInfo.Author = info.Author;
                autoDetailsInfo.Zhaiyao = info.Zhaiyao;
                autoDetailsInfo.Description = info.Description;

                OnBeforeUpdate(autoDetailsInfo);

                bool bl = iService.Update(autoDetailsInfo,id);

                //bool bl = iService.Update(obj, id);
                albumsService.DeleteBatchWhere("Channel = 'Car' and ContentId = '" + autoDetails.Id + "'");
                string[] albumsStr = info.AlbumsPaths.Split(",");
                for (int i = 0; i <= albumsStr.Count() - 1; i++)
                {
                    if (albumsStr[i] != "")
                    {
                        Albums albums = new Albums();
                        albums.Id = GuidUtils.CreateNo();
                        albums.Channel = "Car";
                        albums.ThumbPath = albumsStr[i];
                        albums.OriginalPath = albumsStr[i];
                        albums.ContentId = id;
                        albums.Remark = "";
                        albums.AddTime = DateTime.Now;
                        albumsService.Insert(albums);
                    }
                }
                if (bl)
                {
                    result.ErrCode = ErrCode.successCode;
                    result.ErrMsg = ErrCode.err0;
                    result.Success = true;
                }
                else
                {
                    result.ErrMsg = ErrCode.err43002;
                    result.ErrCode = "43002";
                }
            }  
            return ToJsonContent(result);
        }

        // <summary>
        /// 根据ID获取详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override IActionResult GetById(string id)
        {
            //检查用户是否有权限，否则抛出MyDenyAccessException异常
            CheckAuthorized(AuthorizeKey.ViewKey);
            CommonResult result = new CommonResult();
            try
            {
                result.ResData = new AutoDetailsApp().GetById(id);
                result.Success = true;
            }
            catch (Exception ex)
            {
                var type = MethodBase.GetCurrentMethod().DeclaringType;
                Log4NetHelper.WriteError(type, ex);//错误记录
                result.ErrMsg = ex.Message;
            }
            return ToJsonContent(result);
        }

        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <returns>指定对象的集合</returns>
        [HttpGet]
        public override IActionResult FindWithPager()
        {
            //检查用户是否有权限，否则抛出MyDenyAccessException异常
            CheckAuthorized(AuthorizeKey.ListKey);
            string keywords = Request.Query["search"].ToString() == null ? "" : Request.Query["search"].ToString();
            string orderByDir = Request.Query["order"].ToString() == null ? "" : Request.Query["order"].ToString();
            string orderFlied = Request.Query["sort"].ToString() == "" ? "Id" : Request.Query["sort"].ToString();
            string where = GetPagerCondition();
            bool order = orderByDir == "asc" ? false : true;
            if (!string.IsNullOrEmpty(keywords))
            {
                where += string.Format(" and (Title like '%{0}%'or GoodsCode like '%{0}%'or SubTitle like '%{0}%' or SeoTitle like '%{0}%' or Tags like '%{0}%' or Zhaiyao like '%{0}%')", keywords);
            }
            PagerInfo pagerInfo = GetPagerInfo();
            AutoDetailsApp autoDetailsApp = new AutoDetailsApp();
            List<AutoDetailsDto> list = autoDetailsApp.FindWithPager(where, pagerInfo, orderFlied, order);

            //构造成Json的格式传递
            var result = new
            {
                total = pagerInfo.RecordCount,
                rows = list
            };
            return ToJsonContent(result);
        }
    }
}